package day04.tx.app.service;

import day04.tx.app.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;

@Service
public class Service4 {

    @Autowired
    private AccountMapper accountMapper;

    //事务失效原因 非 public 方法，不支持事务
    //解决方式 1 将方法设置为 public
    //解决方式 2
    //    @Bean
    //    // 只要 beanFactory 的 allowBeanDefinitionOverriding==true, 即使系统的 @Bean 定义没有 @ConditionalOnMissingBean 条件，也会被我们的同名 @Bean 覆盖掉
    //    public TransactionAttributeSource transactionAttributeSource() {
    //        return new AnnotationTransactionAttributeSource(false);
    //    }
    @Transactional
    void transfer(int from, int to, int amount) throws FileNotFoundException {
        int fromBalance = accountMapper.findBalanceBy(from);
        if (fromBalance - amount >= 0) {
            accountMapper.update(from, -1 * amount);
            accountMapper.update(to, amount);
        }
    }
}